//
//  PYCollectionViewController.m
//  WaterFallStream
//
//  Created by zpy on 15/12/5.
//  Copyright © 2015年 zpy. All rights reserved.
//

#import "PYCollectionViewController.h"
#import "PYClothes.h"
#import "PYClothesCell.h"
#import "PYWaterFallFlowLayout.h"
#import <MJExtension.h>
#import <MJRefresh.h>
@interface PYCollectionViewController ()<PYWaterFallFlowLayoutDelegate>

@property(nonatomic,strong) NSMutableArray *clothesArray;
@end

@implementation PYCollectionViewController

static NSString * const reuseIdentifier = @"ClothesCell";
#pragma mark 懒加载
-(NSMutableArray *)clothesArray{

    if (!_clothesArray) {
        _clothesArray = [NSMutableArray array];
    }
    return _clothesArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // 发送请求给服务器
    NSArray *tempArray = [PYClothes objectArrayWithFile:@"clothes.plist"];
    [self.clothesArray addObjectsFromArray:tempArray];
    // 切换布局
    PYWaterFallFlowLayout *layout = [[PYWaterFallFlowLayout alloc] init];
    layout.delegate = self;
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.backgroundColor = [UIColor whiteColor];

    __weak typeof(self) weakSelf = self;
    // 刷新数据
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 加载数据
        NSArray *tempArray = [PYClothes objectArrayWithFilename:@"clothes.plist"];
        [weakSelf.clothesArray insertObjects:tempArray atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, tempArray.count)]];
        [weakSelf.collectionView reloadData];
        
        // 结束刷新
        [weakSelf.collectionView.header endRefreshing];
    }];
    self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 加载数据
        NSArray *tempArray = [PYClothes objectArrayWithFilename:@"clothes.plist"];
        [weakSelf.clothesArray addObjectsFromArray:tempArray];
        [weakSelf.collectionView reloadData];
        
        // 结束刷新
        [weakSelf.collectionView.footer endRefreshing];
    }];
}






-(CGFloat)waterFlowLayout:(PYWaterFallFlowLayout *)layout heightForItemAtIndexpath:(NSIndexPath *)indexPath withItemWidth:(CGFloat)width{

    PYClothes *clothes = self.clothesArray[indexPath.item];
    return clothes.h * width / clothes.w;
}

-(NSUInteger)columnCountInWaterFallFlowLayout:(PYWaterFallFlowLayout *)layout{

    return 3;
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.clothesArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    PYClothesCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.clothes = self.clothesArray[indexPath.item];
    
    return cell;
}



@end
